package com.dk.recite.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dk.recite.entity.Word;
import com.dk.recite.mapper.WordMapper;
import com.dk.recite.service.WordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

@Service
public class WordServiceImpl  extends ServiceImpl<WordMapper, Word> implements WordService {

    public void init(String useKey) throws IOException {
        ClassPathResource classPathResource = new ClassPathResource("word5500");
        InputStream inputStream =classPathResource.getInputStream();
        InputStreamReader isr = new InputStreamReader(inputStream);
        BufferedReader br = new BufferedReader(isr);
        String s = null;
        while((s = br.readLine()) != null) {
            int idx = 0;
            while (s.charAt(idx) != '.') idx++;
            Word word = new Word();
            int length = s.length();
            int i0 = 0;
            int i1 = 1;
            int i2 = 2;
            while (i0 < length && s.charAt(i0) != '.') i0++;
            while (i1 < length && s.charAt(i1) != '[') i1++;
            while (i2 < length && s.charAt(i2) != ']') i2++;

            word.setWordNum(Integer.parseInt(s.substring(0,i0)));
//            System.out.println(Integer.parseInt(s.substring(0,i0)));
            //如果找不到[,]说明没有音标
            if(i1 == length || i2 == length) {
                String[] ss = s.split("\t\t");
                word.setSound(null);
                word.setWord(ss[0].substring(i0 + 1).replaceAll("\"",""));
                word.setFirstLetter((ss[0].substring(i0 + 1).charAt(0) + "").toLowerCase());
                word.setMeans(ss[1].replaceAll("\"",""));
            } else {
                word.setSound(s.substring(i1,i2 + 1));
                word.setWord(s.substring(i0 + 1,i1).trim().replaceAll("\"",""));
                word.setFirstLetter(s.substring(i0 + 1,i1).trim().charAt(0) + "");
                word.setMeans(s.substring(i2 + 1).trim().replaceAll("\"",""));
            }
            word.setUseKey(useKey);
            this.baseMapper.insert(word);
        }
        br.close();
        isr.close();
        inputStream.close();
    }

}
